//
//  KBNetWorkTool.swift
//  KimboWeiBoSwift
//
//  Created by kimbo on 15/12/18.
//  Copyright © 2015年 kimbo. All rights reserved.
//

import UIKit
import AFNetworking

/// 自定义错误
enum KBNetWorkError: Int {
    case emptyAccessToken = -1 //没有accessToken
    case emptyUid = -2 //没有uid
    
    //自定义属性，计算性属性(把错误code和错误描述联系在一起)
    var errorDescrition: String {
        get {
            switch self {
            case KBNetWorkError.emptyAccessToken:
                return "没有accessToken"
            case KBNetWorkError.emptyUid:
                return "没有uid"
            }
        }
    }
    
    //自定义方法,返回一个错误
    private func error() -> NSError {
        return NSError(domain: "cn.itcast.error.network", code: self.rawValue, userInfo: ["errorDescrition": self.errorDescrition])
    }
}


class KBNetWorkTool: AFHTTPSessionManager {

    // MARK: - 属性
    private let client_id = "2238676010" ///appKey
    private let client_secret = "9a502f9dd014fa9e0305ec76523961da" ///app秘钥
    let redirect_uri = "http://www.baidu.com" ///授权回调地址
    
    // MARK: - 方法
    //单例
    static let sharedInstance: KBNetWorkTool = KBNetWorkTool()
    
    //api前面的部分是相同的 "https://api.weibo.com/"
    init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        super.init(baseURL: baseURL!, sessionConfiguration: nil)
        
        //设置序列化器支持"text/plain"
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    /// 登陆界面URL
    func oAuthURL() -> NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        return NSURL(string: urlString)!
    }
    
    /// 用code来获取accessToken
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        //可以省略前面的baseURL,AFN会自动帮我们加上
        let urlString = "oauth2/access_token"
        
        //相关参数
        let parameter = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        POST(urlString, parameters: parameter, success: { (_, result) -> Void in
            //请求成功,回调把结果传回去

            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                
                finished(result: nil, error: error)
        }
    }
    
    /// 加载用户信息
    func loadUserInfo(finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        //守卫：没有值就执行，且往下代码区域可以使用
        guard let access_token = KBUserAccount.loadUserAccount()?.access_token else {
            //来到这里证明没有access_token
            //返回一个自定义错误
            finished(result: nil, error: KBNetWorkError.emptyAccessToken.error())
            return
        }
        
        // TODO: 模拟错误
//        KBUserAccount.loadUserAccount()?.uid = nil
        guard let uid = KBUserAccount.loadUserAccount()?.uid else {
            //来到这里证明没有uid
            //返回一个自定义错误
            finished(result: nil, error: KBNetWorkError.emptyUid.error())
            return
        }
        
        let urlString = "2/users/show.json" //AFN会自动补全
        
        let parameter = [
            "access_token": access_token,
            "uid": uid
        ]
        
        GET(urlString, parameters: parameter, success: { (_, result) -> Void in
            
            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    /// 加载微博
    func loadStatus(since_id: Int, max_id: Int, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        guard let access_token = KBUserAccount.loadUserAccount()?.access_token else {
            finished(result: nil, error: KBNetWorkError.emptyAccessToken.error())
            return
        }
        
        let urlString = "2/statuses/home_timeline.json"
        
        var parameter: [String: AnyObject] = ["access_token": access_token]
        
        if since_id > 0 { //大于0代表别人传来since_id,下拉刷新微博
            parameter["since_id"] = since_id
        } else if max_id > 0 { //大于0代表别人传来max_id,上拉加载更多微博
            parameter["max_id"] = max_id - 1
        }
        
        // debug = true:加载本地微博数据，debug = false:加载网络微博数据
        let debug = false
        if debug {
            loadLocalStatus(finished)
        } else {
            GET(urlString, parameters: parameter, success: { (_, result) -> Void in
                let dict = result as? [String: AnyObject]
                finished(result: dict, error: nil)
                }) { (_, error) -> Void in
                    finished(result: nil, error: error)
            }
        }
        
    }
    
    /// 加载本地微博(以防服务器发生意外，不可以继续开发)
    func loadLocalStatus(finished: (result: [String: AnyObject]?, error:NSError?) -> ()) {
        
        let filePath = NSBundle.mainBundle().pathForResource("LocalStatuses.json", ofType: nil)
        
        let data = NSData(contentsOfFile: filePath!)
        
        // 强制try,和强制拆包一样,如果出现错误.程序立即停止运行
        let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
        
        let dict = json as? [String: AnyObject]
        
        //完成回调
        finished(result: dict, error: nil)
    }
    
    /// 发送微博
    func sendStatus(status: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        guard let access_token = KBUserAccount.loadUserAccount()?.access_token else {
            finished(result: nil, error: KBNetWorkError.emptyAccessToken.error())
            return
        }
        
        let urlString = "2/statuses/update.json"
        
        let parameter = ["access_token": access_token, "status": status]
        
        POST(urlString, parameters: parameter, success: { (_, result) -> Void in
            let dict = result as? [String: AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    
}


